/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.IllegalOrphanException;
import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.Actions;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.SystemAction;
import it.polimi.games.epkb.entityClasses.UpdateKb;
import it.polimi.games.epkb.entityClasses.Rule;
import java.util.ArrayList;
import java.util.Collection;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class ActionsJpaController implements Serializable {

    public ActionsJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }

    public ActionsJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Actions actions) throws PreexistingEntityException, Exception {
        if (actions.getRuleCollection() == null) {
            actions.setRuleCollection(new ArrayList<Rule>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            SystemAction systemAction = actions.getSystemAction();
            if (systemAction != null) {
                systemAction = em.getReference(systemAction.getClass(), systemAction.getId());
                actions.setSystemAction(systemAction);
            }
            UpdateKb updateKb = actions.getUpdateKb();
            if (updateKb != null) {
                updateKb = em.getReference(updateKb.getClass(), updateKb.getId());
                actions.setUpdateKb(updateKb);
            }
            Collection<Rule> attachedRuleCollection = new ArrayList<Rule>();
            for (Rule ruleCollectionRuleToAttach : actions.getRuleCollection()) {
                ruleCollectionRuleToAttach = em.getReference(ruleCollectionRuleToAttach.getClass(), ruleCollectionRuleToAttach.getId());
                attachedRuleCollection.add(ruleCollectionRuleToAttach);
            }
            actions.setRuleCollection(attachedRuleCollection);
            em.persist(actions);
            if (systemAction != null) {
                Actions oldActionsOfSystemAction = systemAction.getActions();
                if (oldActionsOfSystemAction != null) {
                    oldActionsOfSystemAction.setSystemAction(null);
                    oldActionsOfSystemAction = em.merge(oldActionsOfSystemAction);
                }
                systemAction.setActions(actions);
                systemAction = em.merge(systemAction);
            }
            if (updateKb != null) {
                Actions oldActionsOfUpdateKb = updateKb.getActions();
                if (oldActionsOfUpdateKb != null) {
                    oldActionsOfUpdateKb.setUpdateKb(null);
                    oldActionsOfUpdateKb = em.merge(oldActionsOfUpdateKb);
                }
                updateKb.setActions(actions);
                updateKb = em.merge(updateKb);
            }
            for (Rule ruleCollectionRule : actions.getRuleCollection()) {
                Actions oldIdActionOfRuleCollectionRule = ruleCollectionRule.getIdAction();
                ruleCollectionRule.setIdAction(actions);
                ruleCollectionRule = em.merge(ruleCollectionRule);
                if (oldIdActionOfRuleCollectionRule != null) {
                    oldIdActionOfRuleCollectionRule.getRuleCollection().remove(ruleCollectionRule);
                    oldIdActionOfRuleCollectionRule = em.merge(oldIdActionOfRuleCollectionRule);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findActions(actions.getId()) != null) {
                throw new PreexistingEntityException("Actions " + actions + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Actions actions) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Actions persistentActions = em.find(Actions.class, actions.getId());
            SystemAction systemActionOld = persistentActions.getSystemAction();
            SystemAction systemActionNew = actions.getSystemAction();
            UpdateKb updateKbOld = persistentActions.getUpdateKb();
            UpdateKb updateKbNew = actions.getUpdateKb();
            Collection<Rule> ruleCollectionOld = persistentActions.getRuleCollection();
            Collection<Rule> ruleCollectionNew = actions.getRuleCollection();
            List<String> illegalOrphanMessages = null;
            if (systemActionOld != null && !systemActionOld.equals(systemActionNew)) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("You must retain SystemAction " + systemActionOld + " since its actions field is not nullable.");
            }
            if (updateKbOld != null && !updateKbOld.equals(updateKbNew)) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("You must retain UpdateKb " + updateKbOld + " since its actions field is not nullable.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (systemActionNew != null) {
                systemActionNew = em.getReference(systemActionNew.getClass(), systemActionNew.getId());
                actions.setSystemAction(systemActionNew);
            }
            if (updateKbNew != null) {
                updateKbNew = em.getReference(updateKbNew.getClass(), updateKbNew.getId());
                actions.setUpdateKb(updateKbNew);
            }
            Collection<Rule> attachedRuleCollectionNew = new ArrayList<Rule>();
            for (Rule ruleCollectionNewRuleToAttach : ruleCollectionNew) {
                ruleCollectionNewRuleToAttach = em.getReference(ruleCollectionNewRuleToAttach.getClass(), ruleCollectionNewRuleToAttach.getId());
                attachedRuleCollectionNew.add(ruleCollectionNewRuleToAttach);
            }
            ruleCollectionNew = attachedRuleCollectionNew;
            actions.setRuleCollection(ruleCollectionNew);
            actions = em.merge(actions);
            if (systemActionNew != null && !systemActionNew.equals(systemActionOld)) {
                Actions oldActionsOfSystemAction = systemActionNew.getActions();
                if (oldActionsOfSystemAction != null) {
                    oldActionsOfSystemAction.setSystemAction(null);
                    oldActionsOfSystemAction = em.merge(oldActionsOfSystemAction);
                }
                systemActionNew.setActions(actions);
                systemActionNew = em.merge(systemActionNew);
            }
            if (updateKbNew != null && !updateKbNew.equals(updateKbOld)) {
                Actions oldActionsOfUpdateKb = updateKbNew.getActions();
                if (oldActionsOfUpdateKb != null) {
                    oldActionsOfUpdateKb.setUpdateKb(null);
                    oldActionsOfUpdateKb = em.merge(oldActionsOfUpdateKb);
                }
                updateKbNew.setActions(actions);
                updateKbNew = em.merge(updateKbNew);
            }
            for (Rule ruleCollectionOldRule : ruleCollectionOld) {
                if (!ruleCollectionNew.contains(ruleCollectionOldRule)) {
                    ruleCollectionOldRule.setIdAction(null);
                    ruleCollectionOldRule = em.merge(ruleCollectionOldRule);
                }
            }
            for (Rule ruleCollectionNewRule : ruleCollectionNew) {
                if (!ruleCollectionOld.contains(ruleCollectionNewRule)) {
                    Actions oldIdActionOfRuleCollectionNewRule = ruleCollectionNewRule.getIdAction();
                    ruleCollectionNewRule.setIdAction(actions);
                    ruleCollectionNewRule = em.merge(ruleCollectionNewRule);
                    if (oldIdActionOfRuleCollectionNewRule != null && !oldIdActionOfRuleCollectionNewRule.equals(actions)) {
                        oldIdActionOfRuleCollectionNewRule.getRuleCollection().remove(ruleCollectionNewRule);
                        oldIdActionOfRuleCollectionNewRule = em.merge(oldIdActionOfRuleCollectionNewRule);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = actions.getId();
                if (findActions(id) == null) {
                    throw new NonexistentEntityException("The actions with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Actions actions;
            try {
                actions = em.getReference(Actions.class, id);
                actions.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The actions with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            SystemAction systemActionOrphanCheck = actions.getSystemAction();
            if (systemActionOrphanCheck != null) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Actions (" + actions + ") cannot be destroyed since the SystemAction " + systemActionOrphanCheck + " in its systemAction field has a non-nullable actions field.");
            }
            UpdateKb updateKbOrphanCheck = actions.getUpdateKb();
            if (updateKbOrphanCheck != null) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Actions (" + actions + ") cannot be destroyed since the UpdateKb " + updateKbOrphanCheck + " in its updateKb field has a non-nullable actions field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Rule> ruleCollection = actions.getRuleCollection();
            for (Rule ruleCollectionRule : ruleCollection) {
                ruleCollectionRule.setIdAction(null);
                ruleCollectionRule = em.merge(ruleCollectionRule);
            }
            em.remove(actions);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Actions> findActionsEntities() {
        return findActionsEntities(true, -1, -1);
    }

    public List<Actions> findActionsEntities(int maxResults, int firstResult) {
        return findActionsEntities(false, maxResults, firstResult);
    }

    private List<Actions> findActionsEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Actions.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Actions findActions(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Actions.class, id);
        } finally {
            em.close();
        }
    }

    public int getActionsCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Actions> rt = cq.from(Actions.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
